#include "log.h"
#include <string.h>

// 静态函数指针，指向实际的输出函数
static void (*s_printOutput)(const char*) = NULL;

// 全局打印过滤等级 (默认INFO级别)
static volatile PrintLevel_t s_printFilterLevel = PRINT_INFO;

// FreeRTOS 互斥量句柄
static SemaphoreHandle_t s_logMutex = NULL;

// 等级前缀字符串 (节约RAM)
static const char* const levelPrefix[] = 
{
    "[FATAL] ", 
    "[ERROR] ", 
    "[WARN]  ", 
    "[INFO]  ", 
    "[DEBUG] "
};

// 模块初始化
void Print_Init(void (*outputFunc)(const char*))
{
    s_printOutput = outputFunc;
    
    // 如果未设置互斥量，创建一个新的
    if (s_logMutex == NULL)
    {
        s_logMutex = xSemaphoreCreateMutex();
        configASSERT(s_logMutex != NULL);
    }
}

// 设置互斥量 (允许使用外部创建的互斥量)
void Print_SetMutex(SemaphoreHandle_t mutex)
{
    s_logMutex = mutex;
}

// 设置打印等级 (线程安全)
void Print_SetLevel(PrintLevel_t level)
{
    if (s_logMutex != NULL)
    {
        if (xSemaphoreTake(s_logMutex, pdMS_TO_TICKS(10)) == pdTRUE)
        {
            if (level < PRINT_LEVEL_MAX)
            {
                s_printFilterLevel = level;
            }
            xSemaphoreGive(s_logMutex);
        }
    }
    else
    {
        // 没有互斥量时的回退方案
        if (level < PRINT_LEVEL_MAX)
        {
            s_printFilterLevel = level;
        }
    }
}

// 核心打印函数实现 (线程安全)
void Print_Log(PrintLevel_t level, const char* tag, const char* format, ...)
{
    // 检查输出函数是否有效
    if (s_printOutput == NULL)
    {
        return;
    }
    
    // 等级过滤检查
    if (level > s_printFilterLevel)
    {
        return;
    }
    
    // 尝试获取互斥锁 (最多等待10ms)
    BaseType_t mutexAcquired = pdFALSE;
    if (s_logMutex != NULL)
    {
        mutexAcquired = xSemaphoreTake(s_logMutex, pdMS_TO_TICKS(10));
        
        // 获取失败直接返回，避免阻塞
        if (mutexAcquired != pdTRUE)
        {
            return;
        }
    }
    
    // 静态缓冲区避免动态内存分配
    static char logBuffer[128];
    int len = 0;
    
    // 添加等级前缀
    if (level < PRINT_LEVEL_MAX)
    {
        len += snprintf(
            logBuffer + len, 
            sizeof(logBuffer) - len, 
            "%s", 
            levelPrefix[level]
        );
    }
    
    // 添加模块标签
    if (tag != NULL && *tag != '\0')
    {
        len += snprintf(
            logBuffer + len, 
            sizeof(logBuffer) - len, 
            "[%s] ", 
            tag
        );
    }
    
    // 格式化日志内容
    va_list args;
    va_start(args, format);
    len += vsnprintf(
        logBuffer + len, 
        sizeof(logBuffer) - len, 
        format, 
        args
    );
    va_end(args);
    
    // 添加换行符 (根据平台调整)
    if (len < (int)sizeof(logBuffer) - 2)
    {
        logBuffer[len++] = '\r';
        logBuffer[len++] = '\n';
        logBuffer[len] = '\0';
    }
    else
    {
        // 确保缓冲区以空字符结束
        logBuffer[sizeof(logBuffer) - 1] = '\0';
    }
    
    // 输出到设备
    s_printOutput(logBuffer);
    
    // 释放互斥锁
    if (mutexAcquired == pdTRUE)
    {
        xSemaphoreGive(s_logMutex);
    }
}
